﻿' Copyright (c) Microsoft Corporation.  All rights reserved.

Imports MyTravelPostWebsite.MyTravelPostService

Partial Public Class TravelPage
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        ' check the post back
        If IsPostBack Then
            Return
        End If

        ' get the blog id from the page request.
        Dim blogID = 0
        Integer.TryParse(Request.Params("BlogID"), blogID)

        ' create a short lived service and request for latest blog post
        Using travelEntitiesService As New MyTravelPostServiceClient
            Dim blog = travelEntitiesService.GetBlog(blogID)
            Dim post = travelEntitiesService.GetLatestBlogPosting(blog)

            If post IsNot Nothing Then
                ' fill in the new text.
                labelBlogTitle.Text = post.BlogTitle
                labelSeries.Text = blog.SeriesTitle
                labelPerson.Text = blog.BlogWriter.Name
                blogEntry.Text = post.BlogEntry

                ' call the methods to update the comments.
                UpdateCommentsList(post)

                Dim people = travelEntitiesService.GetPeople()

                ' not set all the people in the dropdown list
                dropdownPersons.DataTextField = "Name"
                dropdownPersons.DataSource = people
                dropdownPersons.DataBind()

                dropdownBlogPersonChange.DataTextField = "Name"
                dropdownBlogPersonChange.DataSource = people
                dropdownBlogPersonChange.DataBind()

                ' setup the viewstate that we need in the submit button
                ViewState("BlogPost") = post
                ViewState("People") = people
                ViewState("Blog") = blog
            End If
        End Using
    End Sub

    Private Sub ReloadPage()

        ' get the blog from view state and reload the page so that F5 won't cause problems.
        Dim pageBlog = DirectCast(ViewState("Blog"), Blog)

        ' clear out and then go to the travelpage.
        Response.Redirect("TravelPage.aspx?BlogID=" & pageBlog.BlogID.ToString())
    End Sub
    Protected Sub buttonUpdate_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonUpdate.Click
        ' create the update service
        Using travelEntitiesService As New MyTravelPostServiceClient
            ' here we are going to take every other comment and put (*) at the end.
            ' this is just to show how to make the web service call and update
            ' items on the other end.
            Dim post = DirectCast(ViewState("BlogPost"), BlogPost)
            Dim updatedComments = New List(Of Comment)

            ' this bool value is so we can pass in a subset of items to updated.
            ' basically we want every other comment updated.
            Dim toupdate = True
            For Each c In post.PostComments
                If toupdate Then
                    ' create a new comment, just put the ID, EntityKey, and the new comment 
                    ' text. This will be plenty to update.
                    Dim newComment As New Comment With _
                                            {.CommentID = c.CommentID, _
                                             .CommentText = c.CommentText & "*", _
                                             .EntityKey = c.EntityKey}
                    updatedComments.Add(newComment)
                    toupdate = False
                Else
                    toupdate = True
                End If
            Next

            ' even through the comments are also attached to the post
            ' we can drop and just send the updated items. This helps in 
            ' reducing the amount of data going through the service.
            post.PostComments = travelEntitiesService.UpdateComments(post.PostComments, updatedComments)

            ' update the view state, and be sure to update the gridview
            ViewState("BlogPost") = post
            UpdateCommentsList(post)
        End Using

        ' call reload page so that F5 doesn't cause retries.
        ReloadPage()
    End Sub

    Protected Sub buttonSubmitComment_Click(ByVal sender As Object, ByVal e As EventArgs) Handles buttonSubmitComment.Click
        ' create a short lived service and send back the travel blogs.
        Using travelEntitiesService As New MyTravelPostServiceClient
            Dim post = DirectCast(ViewState("BlogPost"), BlogPost)
            Dim peopleList = ViewState("People")

            ' get the person from the people list
            Dim selectedPerson = DirectCast(peopleList(dropdownPersons.SelectedIndex), Person)

            Dim newComment As New Comment With {.CommentText = textComment.Text}

            ' what we are doing here is setting up the relationships, similar
            ' to a foriegn key. If you didn't have the EntityKey on the reference
            ' then you would have to send all the related ends.
            ' this case we can optimize and build the relationships
            ' and send them down to be added in the ObjectContext.
            newComment.BlogPostReference = New EntityReferenceOfBlogPostBV3qcFOF
            newComment.BlogPostReference.EntityKey = post.EntityKey
            newComment.PersonReference = New EntityReferenceOfPersonBV3qcFOF
            newComment.PersonReference.EntityKey = selectedPerson.EntityKey

            ' save the post comments back to the service
            newComment = travelEntitiesService.AddComment(newComment)

            ' add to the overall list of comments, and update the post.
            newComment.CommentWriter = selectedPerson

            post.PostComments.Add(newComment)

            ' clear the text.
            textComment.Text = ""

            ' call the methods to update the comments on the field
            UpdateCommentsList(post)
        End Using

        ' call reload page so that F5 doesn't cause retries.
        ReloadPage()
    End Sub

    Protected Sub gridComments_RowDeleted(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeletedEventArgs) Handles gridComments.RowDeleted
        ' we did all the work in RowDeleting
    End Sub

    Protected Sub gridComments_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gridComments.RowDeleting
        ' create a short lived service and send back the travel blogs.
        Using travelEntitiesService As New MyTravelPostServiceClient

            ' get the deleted comment and put in the view state list of deleted
            Dim post = DirectCast(ViewState("BlogPost"), BlogPost)

            ' move the comment to the deleted comment selection.
            Dim deletedComment = post.PostComments(e.RowIndex)

            ' setup these comments to be serialized
            post.PostComments.RemoveAt(e.RowIndex)

            ' call the delete comment function
            travelEntitiesService.DeleteComment(deletedComment)

            ' serialize the post and the deleted comments back to view state.
            ViewState("BlogPost") = post

            ' update the comments
            UpdateCommentsList(post)
        End Using

        ' call reload page so that F5 doesn't cause retries.
        ReloadPage()
    End Sub

    Protected Sub UpdateCommentsList(ByRef post As BlogPost)
        ' get all the comments with people and load the comments grid.
        Dim comments = From c In post.PostComments _
                           Select Author = c.CommentWriter.Name, _
                                    WhatISaid = c.CommentText

        ' reset the blog post into comments.
        ViewState("BlogPost") = post
        gridComments.DataSource = comments
        gridComments.DataBind()
    End Sub

    Protected Sub ChangeOwner_Click(ByVal sender As Object, ByVal e As EventArgs) Handles ChangeOwner.Click
        ' create a short lived service and send back the travel blogs.
        Using travelEntitiesService As New MyTravelPostServiceClient

            ' here we are going to take every other comment and put (*) at the end.
            ' this is just to show how to make the web service call and update
            ' items on the other end.
            Dim blog = DirectCast(ViewState("Blog"), Blog)
            Dim peopleList = ViewState("People")

            ' get the person from the people list
            Dim person = DirectCast(peopleList(dropdownBlogPersonChange.SelectedIndex), Person)
            Dim personKey = person.EntityKey

            ' use the key from the person to change the ownship of this blog
            travelEntitiesService.ChangeBlogowner(blog, personKey)
        End Using

        ' call reload page so that F5 doesn't cause retries.
        ReloadPage()
    End Sub
End Class